import * as echarts from 'echarts'
import getOptions from './options'
let parentIdList = []
let mapChart = null
let move = true
function getMapJson(level, id) {
  switch (level) {
    case 'china':
      return require(`@/assets/china`)
    case 'city':
      return require(`@/assets/citys/${id}.json`)
    case 'district':
      return require(`@/assets/county/${id}.json`)
    case 'province':
      return require(`@/assets/province/${id}.json`)
  }
}
function initMap(el) {
  return initChart('china', 'china', 0, el)
}
function initChart(name, level, id, el) {
  const mapJson = getMapJson(level, id)
  const options = getOptions(name, getMapData(mapJson))
  echarts.registerMap(name, mapJson)
  if (!mapChart) {
    mapChart = echarts.init(el)

    window.addEventListener('resize', function() {
      mapChart.resize()
    })
  }
  mapChart.off('click')
  mapChart.off('mousemove')
  mapChart.on('click', enterHandle)
  mapChart.on('mousemove', mousemoveHandle)

  mapChart.setOption(options, true)
}
function getMapData(mapJson) {
  return mapJson.features.map((item) => {
    return {
      id: item.properties.adcode,
      level: item.properties.level,
      name: item.properties.name,
      value: parseInt(Math.random() * 10000),
    }
  })
}
function enterHandle({ event, data }) {
  event.stop()
  if (parentIdList.find((item) => item.level === 'district')) return
  let { name, level, id } = data
  initChart(name, level, id)
  parentIdList.push({ level, id, name })
}
function exitHandle(e) {
  if (move) return
  parentIdList.pop()
  if (parentIdList.length === 0) return initChart('china', 'china', 0)
  let { level, id, name } = parentIdList[parentIdList.length - 1]
  initChart(name, level, id)
}
function mousemoveHandle({ event }) {
  event.event.buttons === 1 ? (move = true) : (move = false)
}

export { initMap, exitHandle }
